package com.woniuxy.rms.service.impl;

import com.woniuxy.rms.dao.AdminMapper;
import com.woniuxy.rms.dao.RolesMapper;
import com.woniuxy.rms.dto.LoginDTO;
import com.woniuxy.rms.pojo.Admins;
import com.woniuxy.rms.pojo.Roles;
import com.woniuxy.rms.service.AdminService;
import com.woniuxy.rms.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Auther: ChenGang  <br/>
 * Date: 2020/3/29 0029:下午 4:14  <br/>
 * Description:管理员服务层
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RolesMapper rolesMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public DataResult login(LoginDTO loginDTO) {
        //数据非空判断
        if (StringUtils.isEmpty(loginDTO.getAccount())){
            return DataResult.failed("用户名不能为空！");
        }
        if (StringUtils.isEmpty(loginDTO.getPassWord())){
            return DataResult.failed("密码不能为空！");
        }
        //传入前端的账户和密码
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginDTO.getAccount(),loginDTO.getPassWord());
        //是否记住我
        try {
            if (loginDTO.isRememberMe()){
                token.setRememberMe(loginDTO.isRememberMe());//记住我
            }
            //认证
            subject.login(token);
            return DataResult.success("登录成功！");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return DataResult.failed("登录失败！用户名或密码错误！");
        }catch (UnknownAccountException e) {
            e.printStackTrace();
            return DataResult.failed("用户名不存在！");
        }catch (AuthenticationException e) {
            e.printStackTrace();
            return DataResult.failed("认证失败！");
        }
    }

    @Override
    public DataResult rigerter(Admins admins, String code) {
        //账户格式验证
        if (admins.getAccount() == null || (!RegexUtil.isUsername(admins.getAccount()))){
            return DataResult.failed("账户格式错误！请输入5-16位由字母组成的账号！");
        }
        //判断验证码是否正确
        if (admins.getPhoneCode() == null || (!admins.getPhoneCode().equals(code))){
            return DataResult.failed("输入验证码错误！");
        }
        //判断密码是否一致
        if (!admins.getPassWord().equals(admins.getRePassWord())){
            return DataResult.failed("两次输入的密码不一致！");
        }
        //密码格式验证
        if (admins.getPassWord() == null || (!RegexUtil.isPassword(admins.getPassWord()))){
            return DataResult.failed("密码格式错误！请输入由数字，字母组成的6-16位密码！");
        }
        //手机号验证
        if (admins.getPhone() == null ||(!RegexUtil.isMobile(admins.getPhone()))){
            return DataResult.failed("请输入正确的手机号！");
        }
        //姓名验证
        if (admins.getAdminName() == null ||(!RegexUtil.isChinese(admins.getAdminName()))){
            return DataResult.failed("请输入正确的姓名！");
        }
        //验证身份证
        if (admins.getAdminCard() == null || (!RegexUtil.isIDCard(admins.getAdminCard()))){
            return DataResult.failed("身份证格式错误！");
        }
        //邮箱验证
        if (admins.getEmail() == null || (!RegexUtil.isEmail(admins.getEmail()))){
            return DataResult.failed("邮箱格式不正确！");
        }
        //查询账户是否重复
        Admins account = adminMapper.findByAccount(admins.getAccount());
        if (account != null){
            return DataResult.failed("该用户名已经被使用！");
        }
        //密码加密处理，账户作为盐值
        Md5Hash md5Hash = new Md5Hash(admins.getPassWord(),admins.getAccount(), HashIteration.NUM);
        admins.setPassWord(md5Hash.toString());
        //将用户信息存进数据库
        adminMapper.insertSelective(admins);
        return DataResult.success("注册成功,即将跳转到登录页面...");
    }

    @Override
    public List<Admins> findByPage(Integer currentPage, Integer pageSize) {

        return adminMapper.findByPage(currentPage,pageSize);
    }

    @Override
    public DataResult editAdminRole(Admins admins) {
        //不能授予超级管理员角色
        Roles roles = rolesMapper.selectByPrimaryKey(admins.getRoleId());
        if (roles.getRole().equals(AdministratorsUtil.ROLE)){
            return DataResult.failed("不能授予超级管理员角色！");
        }
        adminMapper.updateByPrimaryKeySelective(admins);
        //获取管理员邮箱
        Admins admin = adminMapper.selectByPrimaryKey(admins.getId());
        try {
            EmailUtil.sendMail(admin.getEmail(),"尊敬的平台管理员，您已被授予【"+roles.getRole()+"】角色，可执行该角色相关操作！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DataResult.success();
    }

    @Override
    public Admins findById(Long id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    @Override
    public DataResult updateAdmin(Admins admins) {
        //验证身份证
        if (admins.getAdminCard() == null || (!RegexUtil.isIDCard(admins.getAdminCard()))){
            return DataResult.failed("身份证格式错误！");
        }
        //姓名验证
        if (admins.getAdminName() == null ||(!RegexUtil.isChinese(admins.getAdminName()))){
            return DataResult.failed("请输入正确的姓名！");
        }
        //手机号验证
        if (admins.getPhone() == null ||(!RegexUtil.isMobile(admins.getPhone()))){
            return DataResult.failed("请输入正确的手机号！");
        }
        //邮箱验证
        if (admins.getEmail() == null || (!RegexUtil.isEmail(admins.getEmail()))){
            return DataResult.failed("邮箱格式不正确！");
        }
        adminMapper.updateByPrimaryKeySelective(admins);
    return DataResult.success();
    }

    @Override
    public DataResult changePwd(Admins admins, String code) {
        //判断验证码是否正确
        if (admins.getPhoneCode() == null || (!admins.getPhoneCode().equals(code))){
            return DataResult.failed("输入验证码错误！");
        }
        //判断密码是否一致
        if (!admins.getPassWord().equals(admins.getRePassWord())){
            return DataResult.failed("两次输入的密码不一致！");
        }
        //密码格式验证
        if (admins.getPassWord() == null || (!RegexUtil.isPassword(admins.getPassWord()))){
            return DataResult.failed("密码格式错误！请输入由数字，字母组成的6-16位密码！");
        }
        //密码加密处理，账户作为盐值
        Md5Hash md5Hash = new Md5Hash(admins.getPassWord(),admins.getAccount(), HashIteration.NUM);
        admins.setPassWord(md5Hash.toString());
        adminMapper.updateByPrimaryKeySelective(admins);
        return DataResult.success();
    }

    @Override
    public DataResult delete(Long id) {
        adminMapper.deleteByPrimaryKey(id);
        return DataResult.success();
    }
}